<template>
    <div class="relative transition-all duration-300 ease-in-out" :class="collapsed ? 'w-12' : 'w-[350px]'">

        <!-- 折叠状态的工作台 -->
        <div v-if="collapsed" class="w-12 h-full bg-[#1a1a1a] border-r border-gray-700 flex flex-col items-center py-4">
            <!-- 功能快捷按钮 -->
            <div class="flex flex-col space-y-2">
                <!-- 文生3D按钮 -->
                <div class="w-8 h-8 rounded-md cursor-pointer flex items-center justify-center transition-all duration-200 relative group"
                    :class="generatorConfig.mode === 'text'
                        ? 'bg-blue-500 text-white shadow-lg'
                        : 'bg-gray-700 text-gray-400 hover:bg-gray-600 hover:text-gray-300'" @click="setMode('text')"
                    :title="'文生3D'">
                    <el-icon class="text-sm">
                        <Edit />
                    </el-icon>
                    <!-- 选中状态指示器 -->
                    <div v-if="generatorConfig.mode === 'text'"
                        class="absolute -left-1 top-1/2 transform -translate-y-1/2 w-1 h-4 bg-blue-400 rounded-r"></div>
                </div>

                <!-- 图生3D按钮 -->
                <div class="w-8 h-8 rounded-md cursor-pointer flex items-center justify-center transition-all duration-200 relative group"
                    :class="generatorConfig.mode === 'image'
                        ? 'bg-blue-500 text-white shadow-lg'
                        : 'bg-gray-700 text-gray-400 hover:bg-gray-600 hover:text-gray-300'" @click="setMode('image')"
                    :title="'图生3D'">
                    <el-icon class="text-sm">
                        <Picture />
                    </el-icon>
                    <!-- 选中状态指示器 -->
                    <div v-if="generatorConfig.mode === 'image'"
                        class="absolute -left-1 top-1/2 transform -translate-y-1/2 w-1 h-4 bg-blue-400 rounded-r"></div>
                </div>
            </div>

            <!-- 智能推荐状态指示 -->
            <div v-if="smartRecommendation.loading" class="mt-4">
                <div class="w-8 h-8 rounded-md bg-green-500/20 flex items-center justify-center" title="AI分析中">
                    <div class="w-3 h-3 border-2 border-green-500 border-t-transparent rounded-full animate-spin">
                    </div>
                </div>
            </div>

            <!-- 快捷信息 -->
            <div class="mt-auto flex flex-col items-center space-y-2">
                <!-- 设备等级指示 -->
                <div v-if="deviceScore" class="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold"
                    :class="{
                        'bg-green-500 text-white': deviceScore.level === 'high',
                        'bg-yellow-500 text-black': deviceScore.level === 'medium',
                        'bg-red-500 text-white': deviceScore.level === 'low'
                    }" :title="`设备性能: ${deviceScore.level.toUpperCase()}`">
                    {{ deviceScore.level.charAt(0).toUpperCase() }}
                </div>
                <!-- 剩余次数 -->
                <div class="w-6 h-6 rounded-full bg-gray-700 flex items-center justify-center">
                    <span class="text-xs text-gray-300">{{ generatorState.remainingGenerations }}</span>
                </div>
            </div>
        </div>

        <!-- 展开状态的工作台 -->
        <div v-else class="w-[350px] bg-[#1a1a1a] h-full grid grid-rows-[auto_1fr_auto]">
            <!-- 固定在顶部：主要选项卡 -->
            <div class="p-6 pb-0 border-b border-gray-700">
                <div class="flex items-center justify-between mb-6">
                    <div class="flex space-x-4">
                        <div @click="setMode('text')"
                            :class="['cursor-pointer px-4 py-2 rounded-lg transition-all',
                                generatorConfig.mode === 'text' ? 'bg-blue-500 text-white' : 'bg-gray-700 text-gray-300 hover:bg-gray-600']">
                            <div class="flex items-center space-x-2">
                                <el-icon>
                                    <Edit />
                                </el-icon>
                                <span>文生3D</span>
                            </div>
                        </div>
                        <div @click="setMode('image')"
                            :class="['cursor-pointer px-4 py-2 rounded-lg transition-all',
                                generatorConfig.mode === 'image' ? 'bg-blue-500 text-white' : 'bg-gray-700 text-gray-300 hover:bg-gray-600']">
                            <div class="flex items-center space-x-2">
                                <el-icon>
                                    <Picture />
                                </el-icon>
                                <span>图生3D</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 智能推荐状态栏 -->
                <div v-if="smartRecommendation.enabled"
                    class="mb-4 p-3 bg-gray-800/50 rounded-lg border border-gray-700">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-2">
                            <div class="w-2 h-2 rounded-full" :class="{
                                'bg-green-500 animate-pulse': smartRecommendation.loading,
                                'bg-green-500': !smartRecommendation.loading && smartRecommendation.data && !smartRecommendation.applied,
                                'bg-blue-500': smartRecommendation.applied,
                                'bg-red-500': smartRecommendation.error,
                                'bg-gray-500': !smartRecommendation.loading && !smartRecommendation.data && !smartRecommendation.error
                            }">
                            </div>
                            <span class="text-sm text-gray-300">
                                <div v-if="smartRecommendation.loading">AI分析设备中...</div>
                                <div v-else-if="smartRecommendation.data && !smartRecommendation.applied"
                                    class="flex items-center space-x-2">
                                    <span>AI智能推荐已完成</span>
                                    <el-button type="primary" size="small" @click="updateFormConfig"
                                        class="!px-2 !py-1 !text-xs">
                                        更新配置
                                    </el-button>
                                </div>
                                <div v-else-if="smartRecommendation.applied" class="flex items-center space-x-2">
                                    <span>AI推荐已应用</span>
                                    <el-button type="info" size="small" @click="handleRefreshRecommendation"
                                        class="!px-2 !py-1 !text-xs">
                                        重新分析
                                    </el-button>
                                    <el-button type="warning" size="small" @click="resetFormConfig"
                                        class="!px-2 !py-1 !text-xs">
                                        重置
                                    </el-button>
                                </div>
                                <div v-else-if="smartRecommendation.error">AI推荐暂不可用</div>
                                <div v-else>等待AI推荐</div>
                            </span>
                        </div>
                        <el-switch v-model="smartRecommendation.enabled" @change="handleSmartRecommendationToggle"
                            size="small">
                        </el-switch>
                    </div>

                    <!-- 设备信息摘要 -->
                    <div v-if="deviceInfo" class="mt-2 text-xs text-gray-400">
                        {{ getDeviceSummary() }}
                    </div>

                    <!-- 推荐配置预览（当有推荐数据但未应用时显示） -->
                    <div v-if="smartRecommendation.data && !smartRecommendation.applied"
                        class="mt-3 p-2 bg-gray-900/50 rounded border border-gray-600">
                        <div class="text-xs text-gray-400 mb-2 font-medium">AI推荐配置预览:</div>
                        <div class="space-y-1 text-xs text-gray-300">
                            <!-- 任务版本推荐 -->
                            <div v-if="smartRecommendation.data.taskVersionRecommendation" class="flex justify-between">
                                <span>任务版本:</span>
                                <span class="text-blue-400">{{
                                    smartRecommendation.data.taskVersionRecommendation.recommended === 'pro' ? '专业版' :
                                        '快速版' }}</span>
                            </div>
                            <!-- PBR推荐 -->
                            <div v-if="smartRecommendation.data.enablePBRRecommendation" class="flex justify-between">
                                <span>PBR材质:</span>
                                <span class="text-blue-400">{{
                                    smartRecommendation.data.enablePBRRecommendation.recommended ? '启用' : '关闭' }}</span>
                            </div>
                            <!-- 推荐理由 -->
                            <div v-if="smartRecommendation.data.taskVersionRecommendation?.reason"
                                class="mt-2 pt-2 border-t border-gray-600">
                                <div class="text-gray-500">{{ smartRecommendation.data.taskVersionRecommendation.reason
                                }}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 中间滚动区域：动态内容 -->
            <div class="overflow-y-auto px-6 py-6">
                <!-- 表单验证错误提示组件 -->
                <ValidationErrors :errors="generatorState.validationErrors" />

                <!-- AI智能建议组件 -->
                <AiSuggestion :visible="smartSuggestion.visible" :data="smartSuggestion.data"
                    @accept="handleAcceptOptimizedPrompt" @dismiss="handleDismissSuggestion" />

                <!-- 文生3D 界面 -->
                <div v-if="generatorConfig.mode === 'text'" class="space-y-6">
                    <!-- 文本输入区域 -->
                    <div>
                        <div class="text-gray-400 text-sm mb-3 flex items-center justify-between">
                            <span>描述你想要的3D模型</span>
                            <div class="flex items-center space-x-2">
                                <span class="text-xs">智能优化建议</span>
                                <el-switch v-model="smartOptimization.enabled" @change="handleSmartOptimizationToggle"
                                    size="small"></el-switch>
                            </div>
                        </div>

                        <!-- 输入框容器 -->
                        <div class="relative">
                            <el-input v-model="generatorConfig.textConfig.prompt" type="textarea" :rows="4"
                                placeholder="例如：一只可爱的橘猫，卡通风格，高质量细节" class="custom-textarea" maxlength="500"
                                show-word-limit @input="handlePromptInput" />

                            <!-- 智能优化按钮 -->
                            <button v-if="!smartOptimization.enabled" @click="handleManualOptimize"
                                :disabled="!generatorConfig.textConfig.prompt.trim() || isOptimizing"
                                class="absolute left-2 bottom-2 z-10 inline-flex items-center px-2 py-1 text-xs font-medium text-gray-300 bg-gray-700 border border-gray-600 rounded-md hover:bg-gray-600 hover:text-white transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-gray-700 disabled:hover:text-gray-300"
                                :title="!generatorConfig.textConfig.prompt.trim() ? '请先输入描述内容' : '使用AI智能优化提示词'">
                                <svg t="1758682451874" class="icon mr-1" viewBox="0 0 1024 1024" version="1.1"
                                    xmlns="http://www.w3.org/2000/svg" p-id="4708" width="12" height="12">
                                    <path
                                        d="M850.367451 513.489934c4.208858-5.538133 8.271384-11.088546 12.139481-16.651238 55.695486-80.095199 69.303412-153.764036 38.315654-207.435423-30.986735-53.671387-101.583606-78.719876-198.802812-70.535473-6.750751 0.568958-13.588483 1.310855-20.488637 2.187829-2.691295-6.414083-5.467525-12.70844-8.350179-18.838044-41.517579-88.280626-98.512664-136.898927-160.487158-136.898927-61.974493 0-118.969579 48.618301-160.485111 136.898927-2.883677 6.130627-5.658883 12.423961-8.350179 18.839067-6.901177-0.876973-13.739932-1.61887-20.490683-2.187829-97.209996-8.18645-167.813007 16.865109-198.800765 70.535473-30.987758 53.671387-17.380856 127.340223 38.314631 207.435423 3.867074 5.561669 7.9296 11.113105 12.139481 16.651238-4.209882 5.538133-8.271384 11.088546-12.139481 16.651238-55.694463 80.095199-69.301366 153.764036-38.314631 207.434399 27.13808 47.004547 84.658122 72.055083 163.830299 72.055083 11.228739 0 22.897499-0.50449 34.970466-1.51961 6.750751-0.568958 13.589506-1.310855 20.490683-2.187829 2.691295 6.414083 5.467525 12.70844 8.351202 18.839067 41.515532 88.281649 98.510618 136.89995 160.485111 136.89995 61.974493 0 118.969579-48.618301 160.487158-136.89995 2.883677-6.130627 5.658883-12.423961 8.350179-18.839067 6.900154 0.876973 13.737886 1.61887 20.488637 2.187829 12.081153 1.01819 23.737634 1.51961 34.972513 1.51961 79.162968 0 136.693242-25.052582 163.830299-72.055083 30.986735-53.670363 17.379832-127.3392-38.315654-207.434399C858.639858 524.579503 854.577333 519.028067 850.367451 513.489934zM705.378266 258.742972c79.704296-6.715959 138.322345 11.755742 160.790056 50.669006 22.467711 38.914288 9.157567 98.901521-36.513612 164.583452-1.775436 2.554172-3.603061 5.106298-5.459339 7.656377-27.969005-31.598672-61.164035-62.346977-98.369402-91.212398-6.39464-46.653553-16.426111-90.774423-29.806863-130.796952C699.155541 259.309884 702.278671 259.003915 705.378266 258.742972zM603.368964 670.542876c-30.015617 17.32969-60.426231 32.621978-90.675162 45.690622-30.248931-13.068643-60.659545-28.360931-90.675162-45.690622-30.015617-17.32969-58.46353-36.019355-84.905762-55.680137-3.805676-32.730449-5.767354-66.712401-5.767354-101.371782 0-34.659381 1.961678-68.64338 5.768377-101.373829 26.442232-19.660782 54.890144-38.350446 84.904739-55.680137 30.015617-17.32969 60.427254-32.621978 90.675162-45.690622 30.248931 13.068643 60.658522 28.360931 90.675162 45.690622 30.016641 17.32969 58.464553 36.020378 84.907809 55.68116 3.805676 32.730449 5.768377 66.713424 5.768377 101.372805 0 34.659381-1.961678 68.641333-5.767354 101.370759C661.833517 634.522498 633.385605 653.213185 603.368964 670.542876zM679.918407 669.814282c-6.14393 32.457226-14.217816 63.196321-24.11728 91.542926-29.498848-5.600555-60.157101-13.977339-91.338265-24.885783 19.729344-9.582239 39.413662-20.017916 58.912761-31.275307C642.875746 693.938726 661.755746 682.109306 679.918407 669.814282zM460.924741 736.471424c-31.181163 10.908444-61.839417 19.285229-91.337241 24.885783-9.898441-28.346605-17.972327-59.0857-24.116257-91.541903 18.162662 12.295024 37.041638 24.12342 56.539714 35.380812C421.510056 716.454532 441.194374 726.889185 460.924741 736.471424zM293.701159 580.147076c-25.037233-21.548782-47.620577-43.911092-67.219961-66.657142 19.599384-22.74605 42.183751-45.108361 67.219961-66.658166-1.566682 21.877263-2.371 44.142359-2.371 66.658166C291.330158 536.00574 292.134477 558.269813 293.701159 580.147076zM345.471242 357.163539c6.14393-32.457226 14.217816-63.195298 24.116257-91.541903 29.497824 5.600555 60.156078 13.977339 91.336218 24.885783-19.729344 9.582239-39.413662 20.016893-58.912761 31.275307C382.511857 333.040119 363.633904 344.868515 345.471242 357.163539zM564.463885 290.50742c31.18014-10.907421 61.838394-19.284205 91.337241-24.885783 9.898441 28.346605 17.97335 59.0857 24.11728 91.542926-18.162662-12.295024-37.042661-24.124444-56.541761-35.381835C603.877547 310.524313 584.193229 300.088636 564.463885 290.50742zM731.688491 446.832791c25.036209 21.548782 47.620577 43.911092 67.219961 66.657142-19.599384 22.745027-42.182728 45.107337-67.219961 66.656119 1.566682-21.87624 2.371-44.141336 2.371-66.656119C734.059492 490.974128 733.255173 468.710055 731.688491 446.832791zM388.417357 219.247446c34.046421-72.393797 79.343069-113.913423 124.276445-113.913423s90.230024 41.519626 124.275421 113.913423c1.324158 2.815115 2.619664 5.67321 3.900843 8.55484-41.349757 8.422833-84.576257 21.796422-128.176264 39.584554-43.600007-17.788132-86.826508-31.16172-128.176264-39.584554C385.798716 224.919632 387.094222 222.061538 388.417357 219.247446zM195.73494 473.994408c-45.672202-65.680908-58.980299-125.669164-36.513612-164.583452 19.435655-33.662681 65.900919-52.022841 129.693828-52.022841 9.952676 0 20.338211 0.447185 31.096229 1.353834 3.099594 0.260943 6.222725 0.567935 9.359158 0.899486-13.379729 40.021505-23.411199 84.142375-29.806863 130.794905-37.205367 28.865421-70.400397 59.613726-98.370425 91.213421C199.338001 479.099682 197.510376 476.54858 195.73494 473.994408zM320.010361 768.235872c-79.70839 6.711865-138.322345-11.754718-160.790056-50.667983-22.466688-38.913265-9.157567-98.902544 36.513612-164.582429 1.775436-2.554172 3.603061-5.105275 5.458315-7.655354 27.970028 31.598672 61.165058 62.346977 98.370425 91.211375 6.39464 46.65253 16.426111 90.7734 29.806863 130.794905C326.234109 767.667937 323.109955 767.974929 320.010361 768.235872zM636.969223 807.733445c-34.046421 72.392774-79.343069 113.912399-124.275421 113.912399s-90.230024-41.519626-124.276445-113.912399c-1.324158-2.815115-2.620687-5.674233-3.900843-8.556886 41.35078-8.422833 84.577281-21.797445 128.177288-39.585577 43.601031 17.788132 86.827531 31.16172 128.177288 39.584554C639.58991 802.059212 638.293381 804.918329 636.969223 807.733445zM866.168322 717.567889c-22.467711 38.913265-81.075527 57.387012-160.790056 50.667983-3.099594-0.260943-6.222725-0.567935-9.359158-0.899486 13.380752-40.021505 23.412223-84.143399 29.806863-130.795928 37.205367-28.864398 70.399373-59.612703 98.369402-91.210351 1.855254 2.550079 3.682879 5.102205 5.459339 7.656377C875.325889 618.667392 888.633986 678.654624 866.168322 717.567889z"
                                        fill="#6b7280" p-id="4709"></path>
                                </svg>
                                <span>{{ isOptimizing ? '优化中' : '智能优化' }}</span>
                            </button>

                            <!-- 智能优化加载状态指示器 -->
                            <div v-if="smartOptimization.enabled && smartOptimization.loading"
                                class="absolute right-3 bottom-3 z-10">
                                <div
                                    class="w-4 h-4 border border-blue-400 border-t-transparent rounded-full animate-spin">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 图生3D 界面 -->
                <div v-if="generatorConfig.mode === 'image'" class="space-y-6">
                    <!-- 图片类型选择 -->
                    <div class="mb-6">
                        <div class="flex space-x-6 border-b border-gray-700">
                            <div @click="generatorConfig.imageConfig.type = 'single'"
                                :class="['cursor-pointer pb-3 transition-all',
                                    generatorConfig.imageConfig.type === 'single' ? 'text-blue-500 border-b-2 border-blue-500' : 'text-gray-300 hover:text-white']">
                                单张图片
                            </div>
                            <div @click="generatorConfig.imageConfig.type = 'multiple'"
                                :class="['cursor-pointer flex items-center space-x-2 pb-3 transition-all',
                                    generatorConfig.imageConfig.type === 'multiple' ? 'text-blue-500 border-b-2 border-blue-500' : 'text-gray-300 hover:text-white']">
                                <span>多角度图片</span>
                                <el-tag size="small" class="!bg-gray-600 !border-gray-600 !text-gray-300">推荐</el-tag>
                            </div>
                        </div>
                    </div>

                    <!-- 单张图片上传 -->
                    <div v-if="generatorConfig.imageConfig.type === 'single'">
                        <div class="text-gray-400 text-sm mb-3">上传图片</div>
                        <!-- 单张图片上传组件 -->
                        <div class="relative group">
                            <div @click="() => singleImage ? null : $refs.singleInput.click()" :class="[
                                'border-2 border-dashed rounded-lg transition-all cursor-pointer h-28',
                                singleImage
                                    ? 'border-gray-600 bg-gray-800'
                                    : 'border-gray-600 hover:border-blue-500 bg-gray-800/50 hover:bg-gray-800'
                            ]">
                                <!-- 已上传状态 -->
                                <div v-if="singleImage" class="relative w-full h-full">
                                    <img :src="singleImage.url" :alt="singleImage.name"
                                        class="w-full h-full object-cover rounded-lg" />
                                    <!-- 删除按钮 -->
                                    <div @click.stop="handleSingleImageRemove"
                                        class="absolute top-1 right-1 w-6 h-6 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center cursor-pointer transition-colors opacity-0 group-hover:opacity-100">
                                        <el-icon class="text-white text-xs">
                                            <Delete />
                                        </el-icon>
                                    </div>
                                    <!-- 文件信息 -->
                                    <div
                                        class="absolute bottom-0 left-0 right-0 bg-black/60 backdrop-blur-sm text-white text-xs p-1 rounded-b-lg opacity-0 group-hover:opacity-100 transition-opacity">
                                        <div class="truncate">{{ singleImage.name }}</div>
                                    </div>
                                    <!-- 上传状态 -->
                                    <div v-if="!singleImage.uploadedUrl"
                                        class="absolute inset-0 bg-black/50 flex items-center justify-center">
                                        <div class="text-white text-sm">上传中...</div>
                                    </div>
                                </div>

                                <!-- 未上传状态 -->
                                <div v-else class="flex flex-col items-center justify-center h-full text-gray-400 px-4">
                                    <el-icon class="text-2xl mb-2">
                                        <Plus />
                                    </el-icon>
                                    <div class="text-sm text-center">
                                        <div class="font-medium">点击上传图片</div>
                                        <div class="text-xs text-gray-500 mt-1">支持 PNG/JPG/JPEG/WebP，不超过6MB</div>
                                    </div>
                                </div>
                            </div>

                            <!-- 隐藏的文件输入 -->
                            <input ref="singleInput" type="file" accept=".png,.jpg,.jpeg,.webp"
                                @change="handleSingleImageUpload" class="hidden" />
                        </div>
                    </div>

                    <!-- 多角度图片上传 -->
                    <div v-if="generatorConfig.imageConfig.type === 'multiple'">
                        <div class="text-gray-400 text-sm mb-3">上传多角度图片</div>
                        <div class="grid grid-cols-2 gap-3">
                            <!-- 正面图片 - 必传 -->
                            <div class="col-span-2">
                                <div class="text-xs text-gray-400 mb-2 flex items-center">
                                    <span>正面视角</span>
                                    <span class="ml-1 text-red-400">*</span>
                                    <span class="ml-1 text-gray-500">(必传)</span>
                                </div>
                                <div class="relative group">
                                    <div @click="() => multipleImages.front ? null : $refs.frontInput.click()" :class="[
                                        'border-2 border-dashed rounded-lg transition-all cursor-pointer h-28',
                                        multipleImages.front
                                            ? 'border-gray-600 bg-gray-800'
                                            : 'border-gray-600 hover:border-blue-500 bg-gray-800/50 hover:bg-gray-800',
                                        !multipleImages.front ? 'border-red-500/50' : ''
                                    ]">
                                        <!-- 已上传状态 -->
                                        <div v-if="multipleImages.front" class="relative w-full h-full">
                                            <img :src="multipleImages.front.url" :alt="multipleImages.front.name"
                                                class="w-full h-full object-cover rounded-lg" />
                                            <div @click.stop="() => handleMultipleImageRemove('front')"
                                                class="absolute top-1 right-1 w-6 h-6 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center cursor-pointer transition-colors opacity-0 group-hover:opacity-100">
                                                <el-icon class="text-white text-xs">
                                                    <Delete />
                                                </el-icon>
                                            </div>
                                            <div
                                                class="absolute bottom-0 left-0 right-0 bg-black/60 backdrop-blur-sm text-white text-xs p-1 rounded-b-lg opacity-0 group-hover:opacity-100 transition-opacity">
                                                <div class="truncate">{{ multipleImages.front.name }}</div>
                                            </div>
                                            <!-- 上传状态 -->
                                            <div v-if="!multipleImages.front.uploadedUrl"
                                                class="absolute inset-0 bg-black/50 flex items-center justify-center">
                                                <div class="text-white text-sm">上传中...</div>
                                            </div>
                                        </div>

                                        <!-- 未上传状态 -->
                                        <div v-else
                                            class="flex flex-col items-center justify-center h-full text-gray-400 px-4">
                                            <el-icon class="text-2xl mb-2">
                                                <Plus />
                                            </el-icon>
                                            <div class="text-sm text-center">
                                                <div class="font-medium">上传正面图片</div>
                                            </div>
                                        </div>
                                    </div>
                                    <input ref="frontInput" type="file" accept=".png,.jpg,.jpeg,.webp"
                                        @change="(e) => handleMultipleImageUpload(e, 'front')" class="hidden" />
                                </div>
                            </div>

                            <!-- 其他角度的图片上传区域 -->
                            <div v-for="angle in ['back', 'left', 'right']" :key="angle">
                                <div class="text-xs text-gray-400 mb-2">{{ getAngleName(angle) }}</div>
                                <div class="relative group">
                                    <div @click="() => multipleImages[angle] ? null : $refs[angle + 'Input'][0].click()"
                                        :class="[
                                            'border-2 border-dashed rounded-lg transition-all cursor-pointer h-20',
                                            multipleImages[angle]
                                                ? 'border-gray-600 bg-gray-800'
                                                : 'border-gray-600 hover:border-blue-500 bg-gray-800/50 hover:bg-gray-800'
                                        ]">
                                        <div v-if="multipleImages[angle]" class="relative w-full h-full">
                                            <img :src="multipleImages[angle].url" :alt="multipleImages[angle].name"
                                                class="w-full h-full object-cover rounded-lg" />
                                            <div @click.stop="() => handleMultipleImageRemove(angle)"
                                                class="absolute top-1 right-1 w-6 h-6 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center cursor-pointer transition-colors opacity-0 group-hover:opacity-100">
                                                <el-icon class="text-white text-xs">
                                                    <Delete />
                                                </el-icon>
                                            </div>
                                            <!-- 上传状态 -->
                                            <div v-if="!multipleImages[angle].uploadedUrl"
                                                class="absolute inset-0 bg-black/50 flex items-center justify-center">
                                                <div class="text-white text-xs">上传中...</div>
                                            </div>
                                        </div>
                                        <div v-else
                                            class="flex flex-col items-center justify-center h-full text-gray-400 px-2">
                                            <el-icon class="text-xl mb-1">
                                                <Plus />
                                            </el-icon>
                                            <div class="text-xs text-center">
                                                <div class="font-medium">上传{{ getAngleName(angle) }}图片</div>
                                            </div>
                                        </div>
                                    </div>
                                    <input :ref="angle + 'Input'" type="file" accept=".png,.jpg,.jpeg,.webp"
                                        @change="(e) => handleMultipleImageUpload(e, angle)" class="hidden" />
                                </div>
                            </div>
                        </div>

                        <!-- 多角度图片说明 -->
                        <div class="mt-4 p-3 bg-gray-800/50 rounded-lg border border-gray-700">
                            <div class="text-gray-400 text-xs flex items-start space-x-2">
                                <el-icon class="mt-0.5" size="14">
                                    <QuestionFilled />
                                </el-icon>
                                <div>
                                    <div class="font-medium mb-1">多角度拍摄建议:</div>
                                    <ul class="list-disc list-inside space-y-1 text-xs">
                                        <li>正面：物体最具特色的一面，必须上传</li>
                                        <li>背面：物体的背部视角，补充细节信息</li>
                                        <li>左右侧：物体的侧面轮廓，增强立体感</li>
                                        <li>图片背景尽量简洁，主体物品清晰，不超过6MB</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 公共参数设置 -->
                <div class="space-y-6 pt-6 border-t border-gray-700">
                    <!-- 任务版本选择 -->
                    <div>
                        <div class="text-gray-400 text-sm mb-3 flex items-center space-x-2">
                            <span>任务版本</span>
                            <el-tooltip content="专业版支持更多自定义选项，快速版生成更快" placement="top">
                                <el-icon class="text-gray-500 cursor-help">
                                    <QuestionFilled />
                                </el-icon>
                            </el-tooltip>
                        </div>
                        <div class="grid grid-cols-2 gap-3">
                            <div @click="setTaskVersion('pro')" :class="['cursor-pointer p-3 rounded-lg text-center transition-all border',
                                generatorConfig.taskVersion === 'pro'
                                    ? 'bg-blue-500 border-blue-500 text-white'
                                    : 'bg-gray-700 border-gray-600 text-gray-300 hover:border-gray-500']">
                                <div class="font-medium">专业版</div>
                                <div class="text-xs mt-1 opacity-80">
                                    {{ formConfig.taskVersionRecommendation?.recommended === 'pro' ? '✨ AI推荐' : '支持高级选项'
                                    }}
                                </div>
                            </div>
                            <div @click="setTaskVersion('rapid')" :class="['cursor-pointer p-3 rounded-lg text-center transition-all border',
                                generatorConfig.taskVersion === 'rapid'
                                    ? 'bg-blue-500 border-blue-500 text-white'
                                    : 'bg-gray-700 border-gray-600 text-gray-300 hover:border-gray-500']">
                                <div class="font-medium">快速版</div>
                                <div class="text-xs mt-1 opacity-80">
                                    {{ formConfig.taskVersionRecommendation?.recommended === 'rapid' ? '✨ AI推荐' :
                                        '生成速度更快' }}
                                </div>
                            </div>
                        </div>
                        <div v-if="formConfig.taskVersionRecommendation?.reason"
                            class="mt-2 text-xs text-gray-400 bg-gray-800/30 rounded p-2">
                            💡 {{ formConfig.taskVersionRecommendation.reason }}
                        </div>
                    </div>

                    <!-- 模型面数 - 只在专业版显示 -->
                    <div v-if="generatorConfig.taskVersion === 'pro'">
                        <div class="text-gray-400 text-sm mb-3 flex items-center space-x-2">
                            <span>模型面数</span>
                            <el-tag size="small" type="success">专业版专享</el-tag>
                        </div>
                        <div class="grid grid-cols-2 gap-3">
                            <div v-for="face in formConfig.faceOptions" :key="face.value"
                                @click="generatorConfig.commonConfig.faceCount = face.value" :class="['cursor-pointer p-3 rounded-lg text-center transition-all border',
                                    generatorConfig.commonConfig.faceCount === face.value
                                        ? 'bg-blue-500 border-blue-500 text-white'
                                        : 'bg-gray-700 border-gray-600 text-gray-300 hover:border-gray-500']">
                                <div class="font-medium">{{ face.label }}</div>
                                <div class="text-xs mt-1 opacity-80 flex items-center justify-center space-x-1">
                                    <span>{{ face.desc }}</span>
                                    <el-tag v-if="face.tag" size="small" :type="face.tagType"
                                        class="!px-1 !py-0 !text-xs !ml-1">
                                        {{ face.tag }}
                                    </el-tag>
                                </div>
                            </div>
                        </div>
                        <!-- 显示AI推荐理由 -->
                        <div v-if="generatorConfig.commonConfig.faceCount && getCurrentFaceOptionReason() !== '无推荐信息'"
                            class="mt-2">
                            <div class="text-xs text-gray-400 bg-gray-800/30 rounded p-2">
                                💡 {{ getCurrentFaceOptionReason() }}
                            </div>
                        </div>
                    </div>

                    <!-- 快速版面数说明 -->
                    <div v-if="generatorConfig.taskVersion === 'rapid'" class="bg-gray-800/30 rounded-lg p-3">
                        <div class="text-gray-400 text-sm mb-2 flex items-center space-x-2">
                            <el-icon class="text-blue-400">
                                <QuestionFilled />
                            </el-icon>
                            <span>模型面数说明</span>
                        </div>
                        <div class="text-xs text-gray-300">
                            快速版模式下，系统将根据输入内容自动选择最适合的模型面数，无需手动设置。这样可以确保最佳的生成速度和质量平衡。
                        </div>
                    </div>

                    <!-- 生成类型（仅专业版显示） -->
                    <div v-if="generatorConfig.taskVersion === 'pro'">
                        <div class="text-gray-400 text-sm mb-3 flex items-center space-x-2">
                            <span>生成类型</span>
                            <el-tag size="small" type="success">专业版专享</el-tag>
                        </div>
                        <div class="space-y-3">
                            <div v-for="type in formConfig.generateTypeOptions" :key="type.value"
                                @click="generatorConfig.commonConfig.generateType = type.value" :class="['cursor-pointer p-4 rounded-lg border transition-all',
                                    generatorConfig.commonConfig.generateType === type.value
                                        ? 'bg-blue-500/20 border-blue-500'
                                        : 'bg-gray-700/50 border-gray-600 hover:border-gray-500']">
                                <div class="flex justify-between items-center">
                                    <div>
                                        <div class="font-medium">{{ type.name }}</div>
                                        <div class="text-xs text-gray-400 mt-1">{{ type.desc }}</div>
                                    </div>
                                    <div class="flex items-center space-x-2">
                                        <el-tag v-if="type.tag" size="small" :type="type.tagType">{{ type.tag
                                            }}</el-tag>
                                        <div v-if="generatorConfig.commonConfig.generateType === type.value"
                                            class="w-2 h-2 bg-blue-500 rounded-full">
                                        </div>
                                    </div>
                                </div>
                                <!-- 显示AI推荐理由 -->
                                <div v-if="generatorConfig.commonConfig.generateType === type.value && type.reason"
                                    class="mt-2 text-xs text-gray-400 bg-gray-800/30 rounded p-2">
                                    💡 {{ type.reason }}
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 输出格式（仅快速版显示） -->
                    <div v-if="generatorConfig.taskVersion === 'rapid'">
                        <div class="text-gray-400 text-sm mb-3 flex items-center space-x-2">
                            <span>输出格式</span>
                            <el-tag size="small" type="warning">快速版可选</el-tag>
                        </div>
                        <div>
                            <el-select v-model="generatorConfig.commonConfig.resultFormat" class="w-full custom-select"
                                size="small">
                                <el-option v-for="format in formatOptions" :key="format.value" :label="format.label"
                                    :value="format.value" />
                            </el-select>
                        </div>
                    </div>

                    <!-- 高级设置 -->
                    <div>
                        <div class="text-gray-400 text-sm mb-3">高级设置</div>
                        <div class="space-y-3">
                            <!-- PBR材质 -->
                            <div class="flex items-center justify-between">
                                <label class="text-xs text-gray-500 flex items-center space-x-2">
                                    <span>启用PBR材质</span>
                                    <el-tag v-if="formConfig.enablePBRRecommendation?.recommended !== null" size="small"
                                        :type="formConfig.enablePBRRecommendation.recommended ? 'success' : 'info'">
                                        {{ formConfig.enablePBRRecommendation.recommended ? 'AI推荐启用' : 'AI推荐关闭' }}
                                    </el-tag>
                                </label>
                                <el-switch v-model="generatorConfig.commonConfig.enablePBR" size="small"></el-switch>
                            </div>
                            <!-- PBR推荐理由 -->
                            <div v-if="formConfig.enablePBRRecommendation?.reason"
                                class="text-xs text-gray-400 bg-gray-800/30 rounded p-2">
                                💡 {{ formConfig.enablePBRRecommendation.reason }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 固定在底部：生成按钮区域 -->
            <div class="p-6 pt-4 border-t border-gray-700 bg-[#1a1a1a] shadow-lg">
                <!-- 立即生成按钮 -->
                <el-button type="primary" size="large" class="w-full !bg-blue-500 !border-blue-500 !py-3 mb-3"
                    :loading="generatorState.isGenerating" :disabled="!canGenerate" @click="handleGenerate">
                    <template v-if="!generatorState.isGenerating">
                        <svg t="1758528352025" class="icon" viewBox="0 0 1024 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="14601" width="16" height="16">
                            <path
                                d="M332.8 204.8L221.866667 264.533333l64-110.933333L221.866667 42.666667l110.933333 64L443.733333 42.666667 384 153.6l64 110.933333c-4.266667 0-115.2-59.733333-115.2-59.733333zM870.4 640l110.933333-64-64 110.933333 64 110.933334-110.933333-64-110.933333 64 64-110.933334-64-110.933333 110.933333 64zM981.333333 42.666667l-64 110.933333L981.333333 264.533333l-110.933333-64-110.933333 64 64-110.933333L759.466667 42.666667l110.933333 64L981.333333 42.666667z m-388.266666 482.133333l110.933333-110.933333-93.866667-93.866667-110.933333 110.933333 93.866667 93.866667zM640 277.333333L746.666667 384c17.066667 17.066667 17.066667 46.933333 0 64L221.866667 968.533333c-17.066667 17.066667-46.933333 17.066667-64 0l-106.666667-106.666666c-17.066667-17.066667-17.066667-46.933333 0-64L576 277.333333c17.066667-17.066667 46.933333-17.066667 64 0z"
                                p-id="14602" fill="#13227a"></path>
                        </svg>
                        立即生成 3D 模型
                    </template>
                    <template v-else>
                        <span>生成中...</span>
                    </template>
                </el-button>

                <!-- 生成提示 -->
                <div v-if="!canGenerate" class="text-center text-gray-500 text-xs">
                    {{ generateTip }}
                </div>

                <!-- 调试面板组件 -->
                <!-- <DebugPanel :is-development="isDevelopment" :generator-config="generatorConfig"
                    :generator-state="generatorState" :can-generate="canGenerate"
                    :smart-optimization="smartOptimization" /> -->
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import {
    Edit, Picture, QuestionFilled, Plus, Delete
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useGenerator } from '@/hook/useGenerator'
import { useSmartOptimization } from './workBench/hook/useOptimizePrompt'
import { useSmartForm } from '@/hook/useSmartForm'
import ValidationErrors from './workBench/FormValid.vue'
import AiSuggestion from './workBench/AISmart.vue'
import DebugPanel from './workBench/LogInfo.vue'

// 在Vue组件的<script setup>部分添加以下导入
import { uploadFile, validateFile, getImageDimensions } from '@/api/3D-Generator/file-upload'

// =============================================================================
// 防抖工具函数
// =============================================================================

/**
 * 防抖函数
 * @param {Function} func - 要防抖的函数
 * @param {number} delay - 延迟时间(毫秒)
 * @param {Object} options - 配置选项
 * @param {boolean} options.immediate - 是否立即执行第一次
 * @param {number} options.maxWait - 最大等待时间
 * @returns {Function} - 防抖后的函数
 */
function debounce(func, delay = 300, options = {}) {
    let timerId = null
    let maxTimerId = null
    let lastCallTime = 0
    const { immediate = false, maxWait } = options

    const debounced = function (...args) {
        const now = Date.now()

        // 清除之前的定时器
        if (timerId) {
            clearTimeout(timerId)
        }

        // 如果是第一次调用且需要立即执行
        if (!lastCallTime && immediate) {
            func.apply(this, args)
            lastCallTime = now
            return
        }

        // 设置新的延迟执行
        timerId = setTimeout(() => {
            func.apply(this, args)
            lastCallTime = Date.now()
            timerId = null
            if (maxTimerId) {
                clearTimeout(maxTimerId)
                maxTimerId = null
            }
        }, delay)

        // 如果设置了最大等待时间
        if (maxWait && !maxTimerId) {
            maxTimerId = setTimeout(() => {
                if (timerId) {
                    clearTimeout(timerId)
                }
                func.apply(this, args)
                lastCallTime = Date.now()
                timerId = null
                maxTimerId = null
            }, maxWait)
        }

        lastCallTime = now
    }

    // 添加取消方法
    debounced.cancel = function () {
        if (timerId) {
            clearTimeout(timerId)
            timerId = null
        }
        if (maxTimerId) {
            clearTimeout(maxTimerId)
            maxTimerId = null
        }
        lastCallTime = 0
    }

    return debounced
}

// ========== Props ==========
const props = defineProps({
    collapsed: {
        type: Boolean,
        default: false
    }
})

// ========== Emits ==========
const emit = defineEmits(['update:collapsed'])

// ========== 使用生成器Hook ==========
const {
    generatorConfig,
    generatorState,
    handleGenerate,
    setMode,
    setTaskVersion,
    validateForm,
    canGenerate,
    generateTip,
    updateMultipleImagesConfig
} = useGenerator()

// ========== 使用智能优化Hook ==========
const {
    isOptimizing,
    smartOptimization,
    smartSuggestion,
    onSmartOptimizationToggle,
    onPromptInput,
    handleOptimizePrompt,
    acceptOptimizedPrompt,
    dismissSuggestion,
    cleanup
} = useSmartOptimization()

// ========== 使用智能表单Hook ==========
const {
    deviceInfo,
    deviceScore,
    smartRecommendation,
    formConfig,
    getSmartRecommendation,
    applySmartRecommendation,
    resetToDefaultConfig,
    setSmartRecommendationEnabled,
    refreshRecommendation,
    getDeviceSummary
} = useSmartForm()

// ========== 防抖配置 ==========
const DEBOUNCE_CONFIG = {
    // 提示词输入防抖延迟
    PROMPT_INPUT_DELAY: 800,
    // AI推荐刷新防抖延迟
    RECOMMENDATION_DELAY: 1200,
    // 智能优化防抖延迟
    OPTIMIZATION_DELAY: 500,
    // 表单验证防抖延迟
    VALIDATION_DELAY: 300,
    // 最大等待时间
    MAX_WAIT: 2000
}

// ========== 基本配置 ==========
const isDevelopment = process.env.NODE_ENV === 'development'

// ========== 创建防抖函数实例 ==========

// 创建防抖的推荐刷新函数
const debouncedRefreshRecommendation = debounce(
    async (prompt) => {
        if (!prompt || !prompt.trim()) return

        try {
            console.log('执行AI推荐分析:', prompt.substring(0, 50) + '...')
            await refreshRecommendation(prompt)

            if (smartRecommendation.applied) {
                ElMessage({
                    type: 'info',
                    message: '推荐配置已更新',
                    duration: 2000
                })
            }
        } catch (error) {
            console.error('AI推荐分析失败:', error)
        }
    },
    DEBOUNCE_CONFIG.RECOMMENDATION_DELAY,
    {
        immediate: false,
        maxWait: DEBOUNCE_CONFIG.MAX_WAIT
    }
)

// 创建防抖的表单验证函数
const debouncedValidateForm = debounce(
    () => {
        console.log('执行表单验证')
        validateForm()
    },
    DEBOUNCE_CONFIG.VALIDATION_DELAY,
    { immediate: false }
)

// 创建防抖的智能优化函数
const debouncedSmartOptimization = debounce(
    async (prompt) => {
        if (!prompt || !prompt.trim()) return

        try {
            console.log('执行智能优化分析:', prompt.substring(0, 50) + '...')
            await onPromptInput(prompt)
        } catch (error) {
            console.error('智能优化分析失败:', error)
        }
    },
    DEBOUNCE_CONFIG.OPTIMIZATION_DELAY,
    {
        immediate: false,
        maxWait: DEBOUNCE_CONFIG.MAX_WAIT
    }
)

// ========== 智能表单配置更新处理 ==========

/**
 * 应用AI智能推荐配置
 */
const updateFormConfig = () => {
    const success = applySmartRecommendation()
    if (success) {
        debouncedValidateForm()
        console.log('表单配置已更新并重新验证')
    }
}

/**
 * 重置为默认配置
 */
const resetFormConfig = () => {
    resetToDefaultConfig()
    debouncedValidateForm()
    console.log('表单配置已重置为默认值')
}

/**
 * 智能推荐开关处理 - 优化版本
 */
const handleSmartRecommendationToggle = (enabled) => {
    setSmartRecommendationEnabled(enabled)

    if (enabled) {
        const currentPrompt = generatorConfig.value.textConfig.prompt
        if (currentPrompt && currentPrompt.trim()) {
            // 立即执行一次，不使用防抖
            getSmartRecommendation(currentPrompt)
        }
    } else {
        // 取消所有防抖的推荐请求
        if (debouncedRefreshRecommendation.cancel) {
            debouncedRefreshRecommendation.cancel()
        }
        validateForm()
    }
}

/**
 * 刷新推荐配置 - 优化版本
 */
const handleRefreshRecommendation = async () => {
    const currentPrompt = generatorConfig.value.textConfig.prompt

    // 取消之前的防抖请求
    if (debouncedRefreshRecommendation.cancel) {
        debouncedRefreshRecommendation.cancel()
    }

    // 立即执行刷新
    try {
        await refreshRecommendation(currentPrompt)
        if (smartRecommendation.applied) {
            ElMessage({
                type: 'info',
                message: '推荐配置已更新，点击"更新配置"按钮应用新配置',
                duration: 3000
            })
        }
    } catch (error) {
        console.error('刷新推荐配置失败:', error)
        ElMessage.error('刷新失败，请稍后重试')
    }
}

// ========== 智能优化事件处理 ==========

/**
 * 智能优化开关切换处理 - 优化版本
 */
const handleSmartOptimizationToggle = (enabled) => {

    const currentPrompt = generatorConfig.value.textConfig.prompt
    smartOptimization.enabled = enabled
    if (enabled && currentPrompt && currentPrompt.trim()) {
        // 开启时立即执行一次
        onSmartOptimizationToggle(enabled, currentPrompt)
    } else {
        // 关闭时取消防抖请求
        if (debouncedSmartOptimization.cancel) {
            debouncedSmartOptimization.cancel()
        }
        onSmartOptimizationToggle(enabled, currentPrompt)
    }
}

/**
 * 提示词输入处理 - 使用防抖优化
 */
const handlePromptInput = (value) => {
    // 立即执行表单验证（UI响应）
    validateForm()

    // 防抖执行AI相关操作
    if (smartOptimization.enabled && value.trim()) {
        debouncedSmartOptimization(value)
    }

    // 防抖执行推荐分析
    if (smartRecommendation.enabled && value.trim()) {
        debouncedRefreshRecommendation(value)
    }
}

/**
 * 手动优化处理
 */
const handleManualOptimize = async () => {
    const optimizedPrompt = await handleOptimizePrompt(generatorConfig.value.textConfig.prompt)
    if (optimizedPrompt) {
        generatorConfig.value.textConfig.prompt = optimizedPrompt
        validateForm()
    }
}

/**
 * 接受优化建议处理
 */
const handleAcceptOptimizedPrompt = () => {
    const optimizedPrompt = acceptOptimizedPrompt()
    if (optimizedPrompt) {
        generatorConfig.value.textConfig.prompt = optimizedPrompt
        validateForm()
    }
}

/**
 * 忽略建议处理
 */
const handleDismissSuggestion = () => {
    dismissSuggestion()
}

// ========== 本地图片数据管理 ==========
const singleImage = ref(null)
const multipleImages = ref({
    front: null,
    back: null,
    left: null,
    right: null
})

// ========== 配置选项 ==========
const formatOptions = [
    { label: 'GLB格式（推荐）', value: 'GLB' },
    { label: 'OBJ格式', value: 'OBJ' },
    { label: 'FBX格式', value: 'FBX' },
    { label: 'STL格式', value: 'STL' },
    { label: 'USDZ格式', value: 'USDZ' },
    { label: 'MP4格式', value: 'MP4' }
]

// ========== 辅助方法 ==========

/**
 * 获取角度名称
 */
const getAngleName = (angle) => {
    const names = {
        front: '正面',
        back: '背面',
        left: '左侧',
        right: '右侧',
        top: '顶部',
        bottom: '底部'
    }
    return names[angle] || angle
}

/**
 * 获取当前选中面数选项的推荐理由
 */
const getCurrentFaceOptionReason = () => {
    const currentOption = formConfig.value.faceOptions.find(
        option => option.value === generatorConfig.value.commonConfig.faceCount
    )
    return currentOption?.reason || '无推荐信息'
}

/**
 * 文件上传前验证
 */
const beforeUpload = (file) => {
    const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'].includes(file.type)
    if (!isValidType) {
        ElMessage.error('只支持 JPG/PNG/WebP 格式的图片')
        return false
    }

    const isValidSize = file.size / 1024 / 1024 < 6
    if (!isValidSize) {
        ElMessage.error('图片大小不能超过 6MB')
        return false
    }

    return true
}



// 修改创建文件对象的方法
const createFileObject = (file, uploadedUrl = null) => {
    return {
        name: file.name,
        size: file.size,
        type: file.type,
        uid: file.uid || Date.now() + Math.random(),
        status: uploadedUrl ? 'success' : 'uploading',
        url: URL.createObjectURL(file), // 本地预览URL
        uploadedUrl: uploadedUrl, // 后端返回的URL
        raw: file,
        percentage: uploadedUrl ? 100 : 0,
        isUploading: !uploadedUrl
    }
}

// 文件上传到后端的通用方法
const uploadFileToServer = async (file) => {
    try {
        console.log('开始上传文件到后端:', file.name)

        // 验证文件
        const validation = validateFile(file, {
            maxSize: 6 * 1024 * 1024, // 6MB
            allowedTypes: ['image/png', 'image/jpeg', 'image/jpg', 'image/webp']
        })

        if (!validation.valid) {
            throw new Error(validation.error)
        }

        // 获取图片尺寸（可选）
        try {
            const dimensions = await getImageDimensions(file)
            console.log('图片尺寸:', dimensions)

            // 可以添加最小尺寸验证
            if (dimensions.width < 512 || dimensions.height < 512) {
                ElMessage.warning('建议使用512x512像素以上的图片以获得更好效果')
            }
        } catch (error) {
            console.warn('获取图片尺寸失败:', error)
        }

        // 调用上传接口
        const uploadedUrl = await uploadFile(file)
        console.log('文件上传成功:', uploadedUrl)

        if (!uploadedUrl) {
            throw new Error('后端未返回有效的文件URL')
        }

        return uploadedUrl

    } catch (error) {
        console.error('文件上传失败:', error)
        throw error
    }
}

// 修改单张图片上传处理方法
const handleSingleImageUpload = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    try {
        // 先创建文件对象用于预览
        const fileObj = createFileObject(file)
        singleImage.value = fileObj
        generatorConfig.value.imageConfig.singleFiles = [fileObj]

        ElMessage.info('正在上传图片...')

        // 上传到后端
        const uploadedUrl = await uploadFileToServer(file)

        // 上传成功，更新文件对象
        fileObj.uploadedUrl = uploadedUrl
        fileObj.status = 'success'
        fileObj.percentage = 100
        fileObj.isUploading = false

        // 更新配置
        generatorConfig.value.imageConfig.singleFiles = [fileObj]

        validateForm()
        ElMessage.success('图片上传成功')

    } catch (error) {
        // 上传失败，清理状态
        singleImage.value = null
        generatorConfig.value.imageConfig.singleFiles = []
        ElMessage.error(error.message || '图片上传失败，请重试')
    }

    event.target.value = ''
}

// 修改多张图片上传处理方法
const handleMultipleImageUpload = async (event, position) => {
    const file = event.target.files[0]
    if (!file) return

    try {
        // 先创建文件对象用于预览
        const fileObj = createFileObject(file)
        multipleImages.value[position] = fileObj
        generatorConfig.value.imageConfig.multipleAngles[position] = fileObj
        updateMultipleImagesConfig()

        ElMessage.info(`正在上传${getAngleName(position)}图片...`)

        // 上传到后端
        const uploadedUrl = await uploadFileToServer(file)

        // 上传成功，更新文件对象
        fileObj.uploadedUrl = uploadedUrl
        fileObj.status = 'success'
        fileObj.percentage = 100
        fileObj.isUploading = false

        // 更新配置
        generatorConfig.value.imageConfig.multipleAngles[position] = fileObj
        updateMultipleImagesConfig()

        validateForm()
        ElMessage.success(`${getAngleName(position)}图片上传成功`)

    } catch (error) {
        // 上传失败，清理状态
        multipleImages.value[position] = null
        generatorConfig.value.imageConfig.multipleAngles[position] = null
        updateMultipleImagesConfig()
        ElMessage.error(`${getAngleName(position)}图片上传失败: ${error.message}`)
    }

    event.target.value = ''
}

// 修改单张图片移除处理方法
const handleSingleImageRemove = () => {
    if (singleImage.value?.url?.startsWith('blob:')) {
        URL.revokeObjectURL(singleImage.value.url)
    }
    singleImage.value = null
    generatorConfig.value.imageConfig.singleFiles = []
    validateForm()
    ElMessage.info('图片已移除')
}

// 修改多张图片移除处理方法
const handleMultipleImageRemove = (position) => {
    if (multipleImages.value[position]?.url?.startsWith('blob:')) {
        URL.revokeObjectURL(multipleImages.value[position].url)
    }
    multipleImages.value[position] = null
    generatorConfig.value.imageConfig.multipleAngles[position] = null
    updateMultipleImagesConfig()
    validateForm()
    ElMessage.info(`${getAngleName(position)}图片已移除`)
}

// 添加批量上传支持（可选功能）
const handleBatchUpload = async (files) => {
    try {
        ElMessage.info('正在批量上传图片...')

        const uploadPromises = files.map(file => uploadFileToServer(file))
        const uploadedUrls = await Promise.all(uploadPromises)

        ElMessage.success('批量上传完成')
        return uploadedUrls

    } catch (error) {
        ElMessage.error('批量上传失败: ' + error.message)
        throw error
    }
}


// ========== 优化的配置变化监听器 ==========

// 优化配置变化监听器
const debouncedConfigWatcher = debounce(() => {
    console.log('配置变化，执行验证')
    validateForm()
}, DEBOUNCE_CONFIG.VALIDATION_DELAY)

// 监听生成配置变化，使用防抖验证
watch(
    () => [
        generatorConfig.value.commonConfig,
        generatorConfig.value.imageConfig,
        generatorConfig.value.taskVersion
    ],
    () => {
        debouncedConfigWatcher()
    },
    { deep: true }
)

// 优化图片类型切换监听器
watch(() => generatorConfig.value.imageConfig.type, (newType) => {
    // UI操作立即执行，不使用防抖
    if (newType === 'single') {
        Object.keys(multipleImages.value).forEach(key => {
            if (multipleImages.value[key]?.url?.startsWith('blob:')) {
                URL.revokeObjectURL(multipleImages.value[key].url)
            }
        })
        multipleImages.value = { front: null, back: null, left: null, right: null }
        generatorConfig.value.imageConfig.multipleFiles = []
        generatorConfig.value.imageConfig.multipleAngles = {
            front: null, back: null, left: null, right: null, top: null, bottom: null
        }
    } else {
        if (singleImage.value?.url?.startsWith('blob:')) {
            URL.revokeObjectURL(singleImage.value.url)
        }
        singleImage.value = null
        generatorConfig.value.imageConfig.singleFiles = []
    }

    // 验证使用防抖
    debouncedValidateForm()
})

// 优化任务版本切换监听器
watch(() => generatorConfig.value.taskVersion, (newVersion) => {
    console.log('任务版本已切换至:', newVersion)
    if (newVersion === 'rapid') {
        generatorConfig.value.commonConfig.generateType = 'Normal'
    }
    // 使用防抖验证
    debouncedValidateForm()
})

// 监听模式切换
watch(() => generatorConfig.value.mode, () => {
    debouncedValidateForm()
})

// ========== 生命周期优化 ==========

// 组件挂载时初始化
onMounted(async () => {
    if (smartRecommendation.enabled) {
        await getSmartRecommendation(generatorConfig.value.textConfig.prompt)
    }
})

// 组件卸载时清理所有防抖函数和资源
onUnmounted(() => {
    cleanup()

    // 取消所有防抖函数
    if (debouncedRefreshRecommendation.cancel) {
        debouncedRefreshRecommendation.cancel()
    }
    if (debouncedValidateForm.cancel) {
        debouncedValidateForm.cancel()
    }
    if (debouncedSmartOptimization.cancel) {
        debouncedSmartOptimization.cancel()
    }
    if (debouncedConfigWatcher.cancel) {
        debouncedConfigWatcher.cancel()
    }

    // 清理图片资源
    if (singleImage.value?.url?.startsWith('blob:')) {
        URL.revokeObjectURL(singleImage.value.url)
    }
    Object.values(multipleImages.value).forEach(img => {
        if (img?.url?.startsWith('blob:')) {
            URL.revokeObjectURL(img.url)
        }
    })
})

// 暴露方法给父组件
defineExpose({
    validateForm,
    generatorConfig,
    generatorState,
    refreshRecommendation,
    updateFormConfig,
    resetFormConfig,
    applySmartRecommendation,
    smartRecommendation,
    // 暴露防抖函数的取消方法，用于外部控制
    cancelDebounces: () => {
        if (debouncedRefreshRecommendation.cancel) debouncedRefreshRecommendation.cancel()
        if (debouncedValidateForm.cancel) debouncedValidateForm.cancel()
        if (debouncedSmartOptimization.cancel) debouncedSmartOptimization.cancel()
        if (debouncedConfigWatcher.cancel) debouncedConfigWatcher.cancel()
    }
})
</script>

<style scoped>
/* 滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
    width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
    background: #374151;
    border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
    background: #6b7280;
    border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
    background: #9ca3af;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-select) {
    width: 100% !important;
}

:deep(.el-select__wrapper) {
    background: #374151 !important;
    border: 1px solid #4b5563 !important;
    box-shadow: none !important;
    border-radius: 8px !important;
    transition: all 0.3s ease !important;
}

:deep(.el-select .el-select__wrapper:hover) {
    border-color: #6b7280 !important;
    background: #3f3f46 !important;
}

:deep(.el-select .el-select__wrapper.is-focus) {
    border-color: #3b82f6 !important;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1) !important;
    background: #3f3f46 !important;
}

:deep(.el-select .el-input__inner) {
    color: #ffffff !important;
    background: transparent !important;
}

:deep(.el-select .el-input__suffix) {
    color: #9ca3af !important;
}

:deep(.el-select__popper.el-popper) {
    background: #2d2d2d !important;
    border: 1px solid #4b5563 !important;
    border-radius: 8px !important;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3) !important;
}

:deep(.el-select-dropdown__item) {
    color: #e5e7eb !important;
    background: transparent !important;
    transition: all 0.2s ease !important;
}

:deep(.el-select-dropdown__item:hover) {
    background: #374151 !important;
    color: #ffffff !important;
}

:deep(.el-select-dropdown__item.selected) {
    background: #3b82f6 !important;
    color: #ffffff !important;
}

:deep(.el-textarea__inner) {
    background: #374151 !important;
    border: 1px solid #4b5563 !important;
    color: #ffffff !important;
    border-radius: 8px !important;
}

:deep(.el-textarea__inner:focus) {
    border-color: #3b82f6 !important;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1) !important;
}

:deep(.el-textarea .el-input__count) {
    background: transparent;
}

:deep(.el-switch__core) {
    background: #4b5563 !important;
    border-color: #4b5563 !important;
}

:deep(.el-switch.is-checked .el-switch__core) {
    background: #3b82f6 !important;
    border-color: #3b82f6 !important;
}

:deep(.el-tooltip__trigger) {
    display: inline-flex !important;
}
</style>